from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from home_design.models import InspirationVoting, Inspiration
from home_design.serializers import InspirationVotingSerializer

"""___________________灵感投票___________________"""


class InspirationVotingView(APIView):
    permission_classes = [IsAuthenticated]
    """
    投票
    """

    def get_Inspiration_object(self, inspiration_id):
        """
        根据主键获取灵感对象，如果不存在则返回400错误
        """
        try:
            inspiration = Inspiration.objects.get(id=inspiration_id)
        except Inspiration.DoesNotExist:
            return Response({'message': '该灵感不存在'}, status=status.HTTP_400_BAD_REQUEST)
        return inspiration
    def post(self, request,inspiration_id):
        user = request.user
        inspiration = self.get_Inspiration_object(inspiration_id)

        try:
            voting = InspirationVoting.objects.get(user=user, inspiration=inspiration)
        except InspirationVoting.DoesNotExist:
            voting = InspirationVoting.objects.create(user=user, inspiration=inspiration)
        voting.inspiration_voting_status = 1
        voting.save()
        return Response({'message': '投票成功'}, status=status.HTTP_200_OK)


    def delete(self, request, inspiration_id):
        user = request.user
        inspiration = self.get_Inspiration_object(inspiration_id)
        try:
            voting = InspirationVoting.objects.get(user=user, inspiration=inspiration)
        except InspirationVoting.DoesNotExist:
            return Response({'message': '该用户未投票'}, status=status.HTTP_400_BAD_REQUEST)
        voting.inspiration_voting_status = 0
        voting.save()
        return Response({'message': '取消投票成功'}, status=status.HTTP_200_OK)

